package com.browan.background;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper
{
	private DataBase help;
	private SQLiteDatabase mDb;
	private Context mContext;

	private final String DATABASE_NAME = "background.db";

	private final int DATABASE_VERSION = 1;

	public static final String BIG_NAME = "_bigname";

	public static final String SMALL_NAME = "_smallname";

	public static final String BIG_URL = "_bigurl";

	public static final String SMALL_URL = "_smallurl";

	public static final String STYLE = "_style";

	public static final String TABLE_NAME = "_data";

	private static final String CREATE_TABLE = "create table " + TABLE_NAME + "(" + BIG_NAME + " text primary key,"
			+ SMALL_NAME + " text," + BIG_URL + " text," + SMALL_URL + " text," + STYLE + " integer" + ")";

	public DBHelper(Context c)
	{
		this.mContext = c;
		open();
	}

	private class DataBase extends SQLiteOpenHelper
	{

		public DataBase(Context context)
		{
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db)
		{
			db.execSQL(CREATE_TABLE);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
		{
			db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
			onCreate(db);
		}
	}

	public DBHelper open() throws SQLiteException
	{
		help = new DataBase(mContext);
		mDb = help.getWritableDatabase();
		return this;
	}

	public void close()
	{
		mDb.close();
		help.close();
	}

	public void execute(String sql)
	{
		mDb.execSQL(sql);
	}

	public SQLiteDatabase getDb()
	{
		return mDb;
	}

	public boolean isExist(String tableName, String where)
	{
		boolean ret = false;
		Cursor cursor = mDb.query(tableName, null, where, null, null, null, null);
		ret = cursor.getCount() > 0;
		cursor.close();
		return ret;
	}

}